package com.mls.guardian.appst.chain.excutor;

import com.mls.guardian.appst.chain.TaskExecutor;
import com.mls.guardian.appst.chain.TaskInvoker;
import com.mls.guardian.appst.chain.TaskResult;
import com.mls.guardian.appst.shell.ShellScriptExecutorFuture;
import com.mls.guardian.common.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * Created by 2014-400 on 2015-10-26.
 */
public class CleanExcutor implements TaskExecutor {
    private static int MAX_BACKUP_QTY = 30;
    private static final Logger log = LoggerFactory.getLogger(BackupJarExcutor.class);

    @Override
    public TaskResult exec(TaskInvoker invoker) {
        TaskResult result = null;

        log.info("--------开始清理数据操作-------");
        try {
            log.info("----开始清理遗留临时文件----");
            Path bashPath = Paths.get(System.getProperty("user.home"), "guardianConfig");
            FileUtil.deleteFolder(bashPath.toString(), ".+.sh$");
            log.info("----结束清理遗留临时文件----");


            log.info("--------开始清理备份信息-------");
            Path parentPath = Paths.get(invoker.getConfig().getBackupDest());
            File pFile = new File(parentPath.toString());
            if (pFile != null && pFile.listFiles() != null) {
                //遍历各个项目备份
                for (File projectFile : pFile.listFiles()) {
                    if (projectFile.listFiles() != null && projectFile.listFiles().length > 0) {
                        //按最后修改时间先后顺序 排序
                        List<File> childrenFile = Arrays.asList(projectFile.listFiles());
                        childrenFile.sort(new Comparator<File>() {
                            @Override
                            public int compare(File o1, File o2) {
                                if (o1.lastModified() > o2.lastModified()) {
                                    return 1;
                                } else if (o1.lastModified() == o2.lastModified()) {
                                    return 0;
                                } else {
                                    return -1;
                                }
                            }
                        });
                        log.info("--------项目名称[{}],备份个数[{}]-------", projectFile.getName(), childrenFile.size());
                        if (childrenFile.size() > MAX_BACKUP_QTY) {
                            for (int i = 0; i < childrenFile.size() - MAX_BACKUP_QTY; i++) {
                                try {
                                    Path deletePath = Paths.get(projectFile.toString(), childrenFile.get(i).getName());
                                    if (childrenFile.get(i).isDirectory()) {
                                        log.info("--------删除Folder[{}]-------", deletePath.toString());
                                        FileUtil.deleteFolder(deletePath.toString());
                                    } else if (childrenFile.get(i).isFile()) {
                                        log.info("--------删除File[{}]-------", deletePath.toString());
                                        Files.deleteIfExists(deletePath);
                                    }
                                } catch (IOException e) {
                                    log.info("--------清理备份信息[{}]出错[{}]-------", childrenFile.get(i).getName(), e.getMessage());
                                    e.printStackTrace();
                                }
                            }
                        }
                    } else {
                        log.info("--------项目名称[{}],备份未找到-------", projectFile.getName());
                    }
                }//end-for
            } else {
                log.info("--------备份目录下面未找到任何备份-------");
            }
            log.info("--------结束清理备份信息-------");

            result = new TaskResult();
            result.setSuc(true);
        } catch (Exception e) {
            result = new TaskResult();
            result.setSuc(false);
            result.setError(e.getMessage());

            e.printStackTrace();
        } finally {
            log.info("-------结束清理数据操作[{}]-------", result.isSuc());
        }


        if (result.isSuc() == true) {
            return invoker.invoke();
        }

        return result;
    }
}
